import { Socket } from 'socket.io';
const express = require('express');
const jwt = require('jsonwebtoken');
const socketIo = require('socket.io');  
const http = require('http');  
const app = express();
const cors = require('cors');
const server = require('http').createServer(app);
//const io = require('socket.io')(server);
const secretKey = 'your_secret_key';

const io = new socketIo.Server(server, {
  cors: {
    origin: 'http://localhost:5173', // 允许这个源
    methods: ['GET', 'POST'],
    allowedHeaders: ['my-custom-header'],
    credentials: true,
  }
});
// 用于验证 JWT 的中间件
function authenticate(req:any, res:any, next:any) {
  const token = req.headers['authorization'];

  if (!token) {
    return res.status(401).send('Access Denied');
  }

  try {
    const verified = jwt.verify(token, secretKey);
    req.user = verified;
    next();
  } catch (err) {
    res.status(400).send('Invalid Token');
  }
}

app.use(express.json());

// 登录接口，返回 JWT
app.get('/login', (req:any, res:any) => {
  const { username, password } = req.body;
  console.log(username, password);
  if (username && password) {
    const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
    res.json({ token });
  } else {
    res.status(401).send('Access Denied');
  }
});

io.use((socket:Socket, next:any) => {
  const token = socket.handshake.query.token;
  jwt.verify(token, secretKey, (err:any, decoded:any) => {
    if (err) return next(new Error('Authentication error'));
    socket.decoded = decoded;
    next();
  });
});

io.on('connection', (socket:Socket) => {
  console.log(`User ${socket.decoded.username} connected`);
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});